package com.springboot.lock.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;

public class RedisClient {

    private Environment environment;

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisClient.class);

    private JedisPool pool;

    public RedisClient(Environment environment) {
        this.environment = environment;
        init();
    }

    public Object eval(String script, List<String> keys, List<String> args) {
        Jedis jedis = getJedis();
        Object result = jedis.eval(script, keys, args);
        jedis.close();
        return result;
    }

    public String get(final String key){
        Jedis jedis = getJedis();
        String result = jedis.get(key);
        jedis.close();
        return result;
    }

    public String set(final String key, final String value, final String nxxx, final String expx, final int time) {
        Jedis jedis = getJedis();
        String result = jedis.set(key, value, nxxx, expx, time);
        jedis.close();
        return result;
    }

    public void expire(final String key, long expire){
        Jedis jedis = getJedis();
        jedis.pexpire(key, expire);
        jedis.close();
    }

    public Long delete(final String key){
        Jedis jedis = getJedis();
        Long del = jedis.del(key);
        jedis.close();
        return del;
    }

    public void init(){

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(environment.getProperty("spring.redis.jedis.pool.max-active", Integer.class));
        String ip = environment.getProperty("spring.redis.host");
        int port = environment.getProperty("spring.redis.port", Integer.class);
        pool = new JedisPool(jedisPoolConfig, ip,port);
        LOGGER.info("连接池初始化成功 ip={}, port={}",ip,port);
    }

    private Jedis getJedis(){
        return pool.getResource();
    }
}